# -*- coding: utf-8 -*-

"""
    Forrest Cao   2022.11
"""

import sys,os,time, datetime, getopt
from utils import xprint
import logging
import queue
import json
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
from tornado.options import define, options
import tornado.options
from tornado.options import define, options
import handle

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r'/api/.*', handle.EntryHandle),
            (r'.*', handle.BaseHandler)
        ]
        settings = {
            "static_path" : os.path.join(os.path.dirname(__file__), "static"),
            "gzip" : True,
            "debug" : False
        }
        super(Application, self).__init__(handlers, **settings)


def main_service(_listen_port):
    xprint('-------  main service start -------')
    app = Application()
    http_server = tornado.httpserver.HTTPServer(app)
    if _listen_port == 0:
        _listen_port = 18977
    http_server.listen(_listen_port)
    print('XueQing Service start. listening port %d.' % _listen_port)
    tornado.ioloop.IOLoop.instance().start()


from daemon import CDaemon
class ServerDaemon(CDaemon):
    def __init__(self, listen_port, pid_path, home_dir='.', umask=22, verbose=1):
        CDaemon.__init__(self, 'XueQing', pid_path, home_dir, umask, verbose)
        self.listen_port = listen_port
    def run(self, output_fn, **kwargs):
        main_service(self.listen_port)

import logging.config
def init_logging(log_name,configure_file_path="conf_logging.json", default_level=logging.DEBUG, env_key="LOG_CFG"):
    path = configure_file_path
    value = os.getenv(env_key, None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path, "r") as f:
            config = json.load(f)
            config['handlers']['info_file_handler']['filename'] = log_name+'.log'
            logging.config.dictConfig(config)
    else:
        logging.basicConfig(level=default_level)

if __name__ == '__main__':
    help_msg = 'usage: main.py -p <port> -s <start|stop>'
    argv = sys.argv[1:]
    try:
        opts, args = getopt.getopt(argv, "p:s:")
    except:
        print(help_msg)
        sys.exit(1)

    listen_port = 0
    cmd = None
    daemon = False
    for opt, arg in opts:
        if opt in ['-p']:
            if arg.isdigit() == False:
                print('-p error')
                print(help_msg)
                sys.exit(1)
            listen_port = int(arg)
        elif opt in ['-s']:
            cmd = arg
            if cmd == 'start' or cmd == 'stop':
                daemon = True
            else:
                daemon = False

    log_name = './logs/logging'
    init_logging(log_name)

    if daemon == False:
        #front run
        main_service(listen_port)

    else:
        #daemon run
        pid_fn = './xueqing-service.pid'
        #log_fn = '/xueqing-service/%s_%d.log' % (listen_port)
        #err_fn = '/xueqing-service/%s_%d.err.log' % (listen_port)

        cD = ServerDaemon(listen_port, pid_fn, verbose=1)

        if cmd == 'start':
            cD.start(None)
        elif cmd == 'stop':
            cD.stop()
        elif cmd == 'restart':
            cD.restart(None)
        elif cmd == 'status':
            alive = cD.is_running()
            if alive:
                print('process [%s] is running ......' % cD.get_pid())
            else:
                print('daemon process [%s] stopped' % cD.name)
        else:
            print('invalid argument!')
            print(help_msg)






